using JSOCTNet.Card.UtilityBase;
using JSOCTNet.IBIZ;
using JSOCTNet.IDAL;
using JSOCTNetSDK.XmppModel;
using JSOCTNetSDK.XmppModelFun;
using jsxmpp;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Threading;
using Framework.MQ;

namespace JSOCTNetSDK.XmppTask
{
	public class XmppManager : IXmpp, IXmppSend
	{
		private IXmppDown iXmppDown;

		private ISendFile iSendFile;

		private IFileStore iFileStore;

		private CommunicationManager m_CommunicationManager;

		private object m_XmppLock = new object();

		private static XmppManager m_XmppManage;

		private MyServiceRequestHandler m_request = new MyServiceRequestHandler();

		private MyServiceResponseHandler m_response = new MyServiceResponseHandler();

		private BackgroundWorker m_BackWorkerDownRequestProcess = new BackgroundWorker();

        private BackgroundWorker m_BackWorkerDownRequestProcessMQ = new BackgroundWorker();

        private Queue<DownRequestInfo> m_queueDownRequestInfo = new Queue<DownRequestInfo>();

        private Queue<ServiceRequestParam> m_queueDownRequestInfoMQ = new Queue<ServiceRequestParam>();

        private ActiveMQConsumer activeMQConsumer = null;

        private ActiveMQProducer activeMQProducer = null;

        private int checkFailCount;

		public bool IsInitXMPPObj
		{
			get;
			set;
		}

		public static XmppManager Instance
		{
			get
			{
				if (XmppManager.m_XmppManage == null)
				{
					XmppManager.m_XmppManage = new XmppManager();
				}
				return XmppManager.m_XmppManage;
			}
		}

		public string Domain
		{
			get
			{
				return ConfigFile.XmppDomain;
			}
			set
			{
				ConfigFile.XmppDomain = value;
			}
		}

		public string Username
		{
			get
			{
				return ConfigFile.XmppUserName;
			}
			set
			{
				ConfigFile.XmppUserName = value;
			}
		}

		public string Password
		{
			get
			{
				return ConfigFile.XmppPassWord;
			}
			set
			{
				ConfigFile.XmppPassWord = value;
			}
		}

		public string Resource
		{
			get
			{
				return ConfigFile.XmppResource;
			}
			set
			{
				ConfigFile.XmppResource = value;
			}
		}

		public string JIDDataUpload
		{
			get
			{
				return ConfigFile.JIDDataUpload;
			}
			set
			{
				ConfigFile.JIDDataUpload = value;
			}
		}

		public string JIDFileUpload
		{
			get
			{
				return ConfigFile.JIDFileUpload;
			}
			set
			{
				ConfigFile.JIDFileUpload = value;
			}
		}

		public bool IsCheckout
		{
			get
			{
				return ConfigFile.IsCheckout;
			}
			set
			{
				ConfigFile.IsCheckout = value;
			}
		}

		public int Mode
		{
			get
			{
				return ConfigFile.XmppMode;
			}
			set
			{
				ConfigFile.XmppMode = value;
			}
		}

		public int Port
		{
			get
			{
				return ConfigFile.XmppPort;
			}
			set
			{
				ConfigFile.XmppPort = value;
			}
		}

		public bool License
		{
			get
			{
				ConfigFile.License = true;
				return ConfigFile.License;
			}
			set
			{
				ConfigFile.License = true;
			}
		}

		public string BlacklistPath
		{
			get
			{
				return ConfigFile.BlacklistPath;
			}
			set
			{
				ConfigFile.BlacklistPath = value;
			}
		}

		public bool IsRunning
		{
			get;
			set;
		}

		public CommunicationManager Xmpp
		{
			get
			{
				return this.m_CommunicationManager;
			}
		}

		private XmppManager()
		{
			this.IsRunning = true;
			this.m_BackWorkerDownRequestProcess.WorkerReportsProgress = true;
			this.m_BackWorkerDownRequestProcess.WorkerSupportsCancellation = true;
			this.m_BackWorkerDownRequestProcess.DoWork += new DoWorkEventHandler(this.m_BackWorkerDownRequestProcess_DoWork);
			if (!this.m_BackWorkerDownRequestProcess.IsBusy)
			{
				this.m_BackWorkerDownRequestProcess.RunWorkerAsync();
			}

            this.m_BackWorkerDownRequestProcessMQ.WorkerReportsProgress = true;
            this.m_BackWorkerDownRequestProcessMQ.WorkerSupportsCancellation = true;
            this.m_BackWorkerDownRequestProcessMQ.DoWork += M_BackWorkerDownRequestProcessMQ_DoWork;
            this.m_BackWorkerDownRequestProcessMQ.RunWorkerAsync();

            activeMQConsumer = new ActiveMQConsumer("tcp://wxapp.iok.la:51616", "queue1", "demo1", Consumer_Listener);
            activeMQConsumer.Start();
            activeMQProducer = new ActiveMQProducer("tcp://wxapp.iok.la:51616", "queue2", "demo2");

            this.iFileStore = JSOCTNet.IDAL.FactorySync.CreateIFileStore();
			this.iSendFile = FactorySendFile.CreateISendFile();
		}

        private void Consumer_Listener(string obj)
        {
            try
            {
                XmppLogHelper.LogSDKDownData.Info("测试数据：加入队列" + obj);
                ServiceRequestParam serviceRequestParam = null;
                serviceRequestParam = JsonToModel.GetModel(obj, ref serviceRequestParam);

                if (serviceRequestParam != null)
                {
                    lock (this.m_queueDownRequestInfoMQ)
                    {
                        this.m_queueDownRequestInfoMQ.Enqueue(serviceRequestParam);
                    }
                }
            }
            catch (Exception ex)
            {
                XmppLogHelper.LogSDKDownData.Error(ex);
            }
        }

        private void M_BackWorkerDownRequestProcessMQ_DoWork(object sender, DoWorkEventArgs e)
        {
            while (true)
            {
                Thread.Sleep(10);
                try
                {
                    ServiceRequestParam serviceRequestParam = null;

                    lock (this.m_queueDownRequestInfoMQ)
                    {
                        if (this.m_queueDownRequestInfoMQ.Count > 0)
                        {
                            serviceRequestParam = this.m_queueDownRequestInfoMQ.Dequeue();
                        }
                    }

                    if (serviceRequestParam != null)
                    {
                        XmppLogHelper.LogSDKDownData.Info("测试数据：取出队列");
                        ServiceResponseData serviceResponseData = null;
                        if (this.iXmppDown != null)
                        {
                            serviceResponseData = this.iXmppDown.DownRequestProcess(serviceRequestParam);
                        }

                        if (serviceResponseData != null)
                        {
                            string str = ModelToJson.GetJson(serviceResponseData);
                            activeMQProducer.SendMessage(str);
                        }
                    }
                }
                catch (Exception ex)
                {
                    XmppLogHelper.LogSDKDownData.Error(ex);
                }
            }

        }

        public bool IsXmppConnOK(string toUserJID)
		{
			if (ConfigFile.IsStartXmpp)
			{
				bool result = false;
				if (this.Xmpp != null && !string.IsNullOrWhiteSpace(toUserJID))
				{
					int connectionStatus = this.Xmpp.getConnectionStatus(toUserJID);
					if (connectionStatus == 2)
					{
						result = true;
					}
				}
				return result;
			}
			return true;
		}

		private void m_BackWorkerDownRequestProcess_DoWork(object sender, DoWorkEventArgs e)
		{
			while (!this.m_BackWorkerDownRequestProcess.CancellationPending)
			{
				try
				{
					bool flag = false;
					DownRequestInfo downRequestInfo = null;
					lock (this.m_queueDownRequestInfo)
					{
						if (this.m_queueDownRequestInfo != null && this.m_queueDownRequestInfo.Count > 0)
						{
							downRequestInfo = this.m_queueDownRequestInfo.Dequeue();
							flag = true;
						}
					}
					if (flag)
					{
						ServiceRequestParam serviceRequestParam = (ServiceRequestParam)downRequestInfo.ServiceRequestParamObj;
						string json = ModelToJson.GetJson(serviceRequestParam);
						if (ConfigFile.IsPrintlog)
						{
							string strMessage = string.Format("下发数据开始处理:{0} ", json);
							XmppLogHelper.LogSDKUpdateData.Info(strMessage);
						}
						ServiceResponseData serviceResponseData = null;
						if (this.iXmppDown != null)
						{
							serviceResponseData = this.iXmppDown.DownRequestProcess(serviceRequestParam);
						}
						if (serviceResponseData != null)
						{
							if (serviceRequestParam.attributes.Contains("__jht_orig_req_id"))
							{
								if (serviceResponseData.attributes.Contains("__jht_orig_req_id"))
								{
									serviceResponseData.attributes.Remove("__jht_orig_req_id");
								}
								serviceResponseData.attributes.Add("__jht_orig_req_id", serviceRequestParam.attributes["__jht_orig_req_id"]);
							}
							this.Xmpp.responseService(downRequestInfo.FromUser, serviceResponseData, downRequestInfo.ID, downRequestInfo.mode, ConfigFile.IsCheckout);
							XmppLogHelper.LogSDKDownData.Info(string.Format("下发业务处理数据返回：{0}", ModelToJson.GetJson(serviceResponseData)));
						}
						if (ConfigFile.IsPrintlog)
						{
							string strMessage2;
							if (serviceResponseData != null)
							{
								strMessage2 = string.Format("下发处理完成：{0}", ModelToJson.GetJson(serviceResponseData));
							}
							else
							{
								strMessage2 = string.Format("下发处理失败：{0}", json);
							}
							XmppLogHelper.LogSDKUpdateData.Info(strMessage2);
						}
					}
				}
				catch (System.Exception ex)
				{
					XmppLogHelper.LogSDK.Error(ex);
				}
				if (!this.IsRunning)
				{
					return;
				}
				System.Threading.Thread.Sleep(10);
			}
		}

		public void AddFriend()
		{
			bool flag = this.AddFrend(this.JIDDataUpload);
			string format = "将【{0}】加为好友结果为：{1}";
			if (ConfigFile.IsPrintlog)
			{
				XmppLogHelper.LogSDK.Info(string.Format(format, this.JIDDataUpload, flag ? "成功" : "失败"));
			}
			if (this.JIDFileUpload.Trim() != "" && this.JIDFileUpload.Trim() != this.JIDDataUpload.Trim())
			{
				System.Threading.Thread.Sleep(100);
				flag = this.AddFrend(this.JIDFileUpload);
				if (ConfigFile.IsPrintlog)
				{
					XmppLogHelper.LogSDK.Info(string.Format(format, this.JIDFileUpload, flag ? "成功" : "失败"));
				}
			}
		}

		private bool AddFrend(string toUserJID)
		{
			bool result = false;
			if (!string.IsNullOrWhiteSpace(toUserJID))
			{
				this.Xmpp.subScribe(toUserJID, ConfigFile.XmppUserName, "fried");
				result = true;
			}
			return result;
		}

		private void m_request_OnDownRequestHandler(string fromUser, ServiceRequestParam requestParam, string id, string mode)
		{
			if (ConfigFile.IsPrintlog)
			{
				string json = ModelToJson.GetJson(requestParam);
				string str = string.Format("下发数据加入到缓存中:{0} ", json);
				XmppLogHelper.LogSDKUpdateData.Info("XMPP--->" + str);
			}
			DownRequestInfo downRequestInfo = new DownRequestInfo();
			downRequestInfo.DownRequestTime = SpNissp.GetServerTime();
			downRequestInfo.FromUser = fromUser;
			downRequestInfo.ID = id;
			downRequestInfo.mode = mode;
			downRequestInfo.ServiceRequestParamObj = requestParam;
			lock (this.m_queueDownRequestInfo)
			{
				this.m_queueDownRequestInfo.Enqueue(downRequestInfo);
			}
		}

		public bool Create(IXmppDown iXmppDown)
		{
			XmppLogHelper.LogSDK.Info("XMPP--->是否启用XMPP:------" + ConfigFile.IsStartXmpp);
			this.IsInitXMPPObj = false;
			bool flag = false;
			this.iXmppDown = iXmppDown;
			if (!this.IsInitXMPPObj && this.m_CommunicationManager != null)
			{
				this.m_CommunicationManager.Dispose();
				this.m_CommunicationManager = null;
			}
			if ((this.m_CommunicationManager == null || !this.IsInitXMPPObj) && this.Domain != "" && this.Username != "" && this.Resource != "" && this.Password != "")
			{
				XmppLogHelper.LogSDK.Info("开始初始化XMPP组件。。。。。。");
				this.m_CommunicationManager = new CommunicationManager(this.Domain, this.Username, this.Resource, this.Password, this.BlacklistPath, this.Port);
			}
			if (this.m_CommunicationManager != null)
			{
				this.m_request.OnDownRequestHandler += new MyServiceRequestHandler.DownRequestHandler(this.m_request_OnDownRequestHandler);
				this.m_response.OnUploadResultHandler += new MyServiceResponseHandler.UploadResultHandler(this.iXmppDown.UploadResultProcess);
				this.m_CommunicationManager.RegisterRequestHandler(this.m_request);
				this.m_CommunicationManager.RegisterResponseHandler(this.m_response);
				this.m_CommunicationManager.setShowLog(ConfigFile.IsPrintlog);
				this.IsInitXMPPObj = true;
				flag = true;
			}
			XmppLogHelper.LogSDK.Info(string.Format("初始化XMPP组件结束：初始化【{0}】", flag ? "成功" : "失败"));
			for (int i = 0; i < 6; i++)
			{
				System.Threading.Thread.Sleep(1000);
			}
			this.AddFriend();
			if (!this.IsXmppConnOK())
			{
				string strMessage = "捷慧通集成服务连接失败，请检查XMPP服务配置是否正确";
				XmppLogHelper.LogSDK.Info(strMessage);
				flag = false;
			}
			else
			{
				string strMessage2 = "捷慧通集成服务连接成功！";
				XmppLogHelper.LogSDK.Info(strMessage2);
				flag = true;
			}
			new System.Threading.Thread(new System.Threading.ThreadStart(this.CheckXMPPStatus))
			{
				IsBackground = true
			}.Start();
			return flag;
		}

		private void CheckXMPPStatus()
		{
			for (int i = 0; i < 12; i++)
			{
				System.Threading.Thread.Sleep(10000);
			}
			string text = "{0}@{1}/{2}";
			string arg = ConfigFile.JIDDataUpload.Substring(ConfigFile.JIDDataUpload.IndexOf("@") + 1, ConfigFile.JIDDataUpload.IndexOf("/") - ConfigFile.JIDDataUpload.IndexOf("@") - 1);
			text = string.Format(text, ConfigFile.XmppUserName, arg, ConfigFile.XmppResource);
			this.AddFrend(text);
			while (this.IsRunning)
			{
				ServiceRequestParam serviceRequestParam = new ServiceRequestParam();
				ServiceResponseData serviceResponseData = new ServiceResponseData();
				serviceResponseData.resultCode = 101;
				serviceRequestParam.serviceId = "md.card.data.delaycheckrequst";
				serviceRequestParam.seqId = System.Guid.NewGuid().ToString("N");
				TXDataObject tXDataObject = new TXDataObject();
				tXDataObject.operateType = "READ";
				tXDataObject.attributes.Add("cardId", "测试车牌");
				this.Xmpp.syncRequestService(text, serviceRequestParam, 0, false, 5000, ref serviceResponseData);
				bool flag = serviceResponseData.resultCode == 1 || serviceResponseData.resultCode == 0;
				if (flag)
				{
					this.checkFailCount = 0;
				}
				else
				{
					this.checkFailCount++;
					XmppLogHelper.LogSDK.Info(string.Format("检测失败次数：{0}", this.checkFailCount));
				}
				if (this.checkFailCount > 2)
				{
					XmppLogHelper.LogSDK.Info(string.Format("检测失败次数：{0}", this.checkFailCount));
					XmppLogHelper.LogSDK.Info("服务主动退出！");
					System.Environment.Exit(1);
				}
				for (int j = 0; j < ConfigFile.CheckXMPPInterval; j++)
				{
					if (!this.IsRunning)
					{
						return;
					}
					System.Threading.Thread.Sleep(1000);
				}
			}
		}

		public void Stop()
		{
			this.IsRunning = false;
			if (!this.m_BackWorkerDownRequestProcess.CancellationPending)
			{
				this.m_BackWorkerDownRequestProcess.CancelAsync();
			}
			this.Xmpp.Dispose();
		}

		public ServiceResponseData requestService(ServiceRequestParam requestParam, string strServiceID, string strSeqID, string TaskName)
		{
			ServiceResponseData serviceResponseData = new ServiceResponseData();
			serviceResponseData.resultCode = 404;
			System.DateTime arg_16_0 = System.DateTime.Now;
			try
			{
				if (string.IsNullOrWhiteSpace(strSeqID))
				{
					requestParam.seqId = Common.GUId();
					strSeqID = requestParam.seqId;
				}
				else
				{
					requestParam.seqId = strSeqID;
				}
				string json = ModelToJson.GetJson(requestParam);
				XmppLogHelper.LogSDKUpdateData.Info("HTTP--->请求参数ServiceRequestParam：" + json);
				string text = HttpSubmit.PostRequest(ConfigFile.HttpUpUrl, System.Text.Encoding.UTF8, json);
				XmppLogHelper.LogSDKUpdateData.Info("HTTP--->请求返回ServiceResponseData：" + text);
				serviceResponseData = JsonToModel.GetModel(text, ref serviceResponseData);
			}
			catch (System.Exception ex)
			{
				XmppLogHelper.LogSDKUpdateData.Error("HTTP 发送异常", ex);
			}
			serviceResponseData.seqId = strSeqID;
			serviceResponseData.serviceId = strServiceID;
			return serviceResponseData;
		}

		public bool IsXmppConnOK()
		{
			int i = 0;
			bool flag = false;
			while (i < 6)
			{
				if (!(this.JIDDataUpload.Trim() != ""))
				{
					flag = false;
					break;
				}
				flag = this.IsXmppConnOK(this.JIDDataUpload);
				if (flag)
				{
					flag = true;
					break;
				}
				System.Threading.Thread.Sleep(3000);
				i++;
			}
			return flag;
		}

		public bool SendFile(FileDescription fileDescription, int type)
		{
			bool result = false;
			string text = this.iFileStore.Get();
			if (text == null)
			{
				return false;
			}
			if (this.iSendFile != null)
			{
				this.iSendFile.Init(text);
				string json = ModelToJson.GetJson(fileDescription);
				int num = this.iSendFile.Send(this.Username, json);
				if (num == 0)
				{
					result = true;
				}
				else if (num == 1)
				{
					result = false;
				}
				else if (num == 100)
				{
					this.iFileStore.Set(null);
					System.Threading.Thread.Sleep(20000);
					result = false;
				}
				else if (num == 101)
				{
					this.iFileStore.Set(null);
					System.Threading.Thread.Sleep(20000);
					result = false;
				}
				return result;
			}
			return false;
		}
	}
}
